package com.km.wskj.itmonitor.pager.monitor.application;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.App;
import com.km.wskj.itmonitor.model.Server;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.monitor.server.ServerDetailActivity;
import com.km.wskj.itmonitor.pager.monitor.server.ServerListActivity;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;


import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

/**
 * @author by Xianling.Zhou on 2017/3/3.
 */

public class AppListActivity extends LActivity {

    private static final String TAG = "AppListActivity";

    //ui
    @BindView(R.id.tool_bar_back)
    ImageView mBack;
    @BindView(R.id.tool_bar_title)
    TextView mTitle;
    @BindView(R.id.app_zrclistview)
    ZrcListView mZrcListView;

    //data
    private MyAdapter mAdapter;
    private List<App> apps;


    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 2000);// 50ms后执行this，即runable
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_application);
        ButterKnife.bind(this);
        //沉浸式
        StatusBarCompat.compat(context, getResources().getColor(R.color.colorWs_blue));
        mTitle.setText("应用系统");
        mBack.setVisibility(View.VISIBLE);
        initData();
//        handler.postDelayed(runnable, 2000);
    }

    private void initData() {

        pdc.appList(HTTP_TASK_TAG, new ZxlGenericsCallback<List<App>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                mZrcListView.setRefreshFail("数据获取失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<App> as, int i) {
                apps = as;

                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

            }
        });

        initPullToRefresh();

    }

    private void initPullToRefresh() {
        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#f1f1f1"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                App app = (App) parent.getItemAtPosition(position);
                Intent intent = new Intent(context, AppNameTargetActivity.class);
                intent.putExtra("id", app.id);
                startActivity(intent);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);
    }

    private void onRefresh() {
        pdc.appList(HTTP_TASK_TAG, new ZxlGenericsCallback<List<App>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                mZrcListView.setRefreshFail("数据获取失败！");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<App> as, int i) {
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();
            }
        });
    }

    private void onLoadMore() {

        pdc.appList(HTTP_TASK_TAG, new ZxlGenericsCallback<List<App>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                mZrcListView.setRefreshFail("数据获取失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<App> as, int i) {

                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setLoadMoreSuccess();
            }
        });

    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (apps == null) {
                return 0;
            }
            return apps.size();
        }

        @Override
        public Object getItem(int position) {
            App item = apps.get(position);
            return item;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.app_list_item);
            App item = apps.get(position);
            helper.setText(R.id.tv_app_name, item.appSortName);
            helper.setText(R.id.tv_app_used, item.rat + "%");

            if (item.isAlive) {
                helper.setBackgroundColor(R.id.tv_app_state, getResources().getColor(R.color.text_green_night));
                helper.setText(R.id.tv_app_state, "正常");
            } else {
                helper.setBackgroundColor(R.id.tv_app_state, getResources().getColor(R.color.darkorange));
                helper.setText(R.id.tv_app_state, "异常");
            }
            return helper.getView();
        }
    }


    @OnClick(R.id.tool_bar_back)
    public void back() {
        finish();
    }
}
